package net.zretc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import net.zretc.entity.Admin;
import net.zretc.mapper.AdminMapper;
import net.zretc.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public boolean register(Admin admin) {
        // 检查用户名是否已存在
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", admin.getUsername());
        Admin existingAdmin = adminMapper.selectOne(queryWrapper);

        if (existingAdmin != null) {
            System.err.println("注册失败：用户名已存在，查询到的管理员: " + existingAdmin);
            return false;
        }

        // 设置创建时间
        admin.setCreateTime(new Date());

        try {
            System.out.println("准备插入管理员信息: " + admin);
            int result = adminMapper.insert(admin);
            System.out.println("插入结果: " + result);
            return result > 0;
        } catch (Exception e) {
            System.err.println("注册插入数据库出错: " + e.getMessage());
            e.printStackTrace(); // 打印详细的异常堆栈信息
            return false;
        }
    }

    @Override
    public Admin login(String username, String password) {
        Admin admin = new Admin();
        admin.setUsername(username);
        admin.setPassword(password);
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>(admin);
        return adminMapper.selectOne(queryWrapper);
    }

}